package com.victor.controller;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.victor.entity.ContrastRecord;
import com.victor.entity.Picturebook;
import com.victor.entity.Publicity;
import com.victor.entity.User;
import com.victor.entity.Vote;
import com.victor.service.PicService;
import com.victor.service.VoteService;
import com.victor.utils.AddressUtils;
import com.victor.utils.GetOpenidUtil;
import com.victor.utils.IpUtils;
import com.victor.utils.Msg;

/**
 * 投票
 * 
 * @author Mr.Zhang
 *
 */
@RestController
@RequestMapping("/vote")
public class VoteController {

	@Autowired
	private VoteService voteService;
	@Autowired
	private PicService picService;
	
	@Autowired
	HttpServletRequest request;

	// 通过code获取openid
	@RequestMapping("/getOpenid")
	public Msg getOpenid(String code) {
		System.out.println(code);

		if (code == null) {
			return Msg.fail("参数错误");
		}
		String openid = "";
		try {
			openid = GetOpenidUtil.getopenid(code);
		} catch (Exception e) {
			e.printStackTrace();
		}
		if (openid == null || openid.equals("")) {
			return Msg.fail("参数错误");
		}

		// 通过openid查询user表
		User user = voteService.getUserByOpenid(openid);
		if (user != null) {
			return Msg.fail("您已参加过投票，请勿重复投票！");
		}

		return Msg.success().add("openid", openid);
	}

	// 通过openid查询该用户是否已经参加过投票
	@RequestMapping("/ifJoinVote")
	public Msg ifJoinVote(String openid) {
		User user = voteService.ifJoinVote(openid);
		// 如果通过openid能查询出用户 则说明该用户参加过投票
		if (user != null) {
			return Msg.fail("您已参加过投票,请勿重复投票");
		}
		return Msg.success();
	}

	// 通过绘本名模糊查询绘本list
	@RequestMapping("/getpicbooklist")
	public Msg getpicbook(String picname) {
		List<Picturebook> picbooks = picService.getPicturebooksByPicname(picname);
		return Msg.success().add("picbooks", picbooks);
	}

	// 投票提交
	@RequestMapping("/submitVote")
	public Msg submitVote(@RequestBody User user) {
		String ipAddress = IpUtils.getIpAddress(request);
		System.out.println(ipAddress);
		if (user == null) {
			return Msg.fail("参数错误");
		}

		user.setVoteaddress("");
		if (!ipAddress.equals("")) {
			String address = AddressUtils.getAddresses("ip=" + ipAddress);
			user.setVoteaddress(address);
		}
		// 获取投票的绘本list
		List<Vote> votes = user.getVotes();
		// 将user信息插入到数据库
		// boolean insUser =
		voteService.addUserMsg(user);
		if (votes == null) {
			return Msg.fail("votes参数为空");
		}
		for (Vote vote : votes) {
			if (vote.getPid() == null) {// 如果传入绘本id是空，则是数据库中没有的
				// 将用户id插入到投票表中
				vote.setUserid(String.valueOf(user.getId()));
				if (user.getAgegroup() != null) {
					vote.setAgegroup(user.getAgegroup());
				}
				// 将votes信息插入到数据库
				// boolean insVote =
				voteService.addVote(vote);

				// 通过书名和年龄段查询公示表是否存在该书
				if (vote.getAgegroup().equals("1") || vote.getAgegroup().equals("2") || vote.getAgegroup().equals("3") || vote.getAgegroup().equals("4") || vote.getAgegroup().equals("5") || vote.getAgegroup().equals("6")) {// 如果投票是家长投的,不管选择哪个年龄段，都算家长投票
					vote.setAgegroup("0");
				}
				// 通过投票书名和年龄段查询该书是否被投过票
				Publicity publicity = voteService.ifJoinPublicity(vote.getPicname(), vote.getAgegroup());
				if (publicity != null) {// 如果存在:拿到投票次数,将次数加1,更新数据库
					String newNumberofvote = String.valueOf(Integer.valueOf(publicity.getNumberofvote()) + 1);
					publicity.setNumberofvote(newNumberofvote);
					// boolean updPublicity =
					voteService.updPublicity(publicity);
				} else {// 如果不存在:将书名,作者,1次,和年龄段存入数据库

					publicity = new Publicity();
					publicity.setPicname(vote.getPicname());
					publicity.setAuthor(vote.getAuthor());
					publicity.setNumberofvote("1");
					publicity.setAgegroup(vote.getAgegroup());

					// boolean insPublicity =
					voteService.insPublicity(publicity);
				}
			} else {

				// 通过pid查询绘本名和作者
				Picturebook picturebook = picService.getPicturebookById(vote.getPid());

				// 将用户id插入到投票表中
				vote.setUserid(String.valueOf(user.getId()));
				if (user.getAgegroup() != null) {
					vote.setAgegroup(user.getAgegroup());
				}
				vote.setPicname(picturebook.getPName());// 从picturebook获取书名
				vote.setAuthor(picturebook.getPAuthor());// 从picturebook获取作者
				// 将votes信息插入到数据库
				// boolean insVote =
				voteService.addVote(vote);

				// 通过书名和年龄段查询公示表是否存在该书
				if (vote.getAgegroup().equals("1") || vote.getAgegroup().equals("2") || vote.getAgegroup().equals("3") || vote.getAgegroup().equals("4") || vote.getAgegroup().equals("5") || vote.getAgegroup().equals("6")) {// 如果投票是家长投的,不管选择哪个年龄段，都算家长投票
					vote.setAgegroup("0");
				}
				// 通过投票书名和年龄段查询该书是否被投过票
				Publicity publicity = voteService.ifJoinPublicity(picturebook.getPName(), vote.getAgegroup());
				if (publicity != null) {// 如果存在:拿到投票次数,将次数加1,更新数据库
					String newNumberofvote = String.valueOf(Integer.valueOf(publicity.getNumberofvote()) + 1);
					publicity.setNumberofvote(newNumberofvote);
					// boolean updPublicity =
					voteService.updPublicity(publicity);
				} else {// 如果不存在:将书名,作者,1次,和年龄段存入数据库

					publicity = new Publicity();
					publicity.setPicname(picturebook.getPName());
					publicity.setAuthor(picturebook.getPAuthor());
					publicity.setNumberofvote("1");
					publicity.setAgegroup(vote.getAgegroup());

					// boolean insPublicity =
					voteService.insPublicity(publicity);
				}
			}

		}
		return Msg.success();
	}

	// 获取投票公示信息
	@RequestMapping("/getAllPublicity")
	public Msg getAllPublicity() {
		// 拿到所有的公示数据
		List<Publicity> publicitys = voteService.getAllPublicity();

		Integer totle = voteService.getTotleUser();

		List<Publicity> jzPublicitys = new ArrayList<Publicity>();// 家长学生投票list
		List<Publicity> yedbPublicitys = new ArrayList<Publicity>();// 幼儿大班投票list
		List<Publicity> yexbPublicitys = new ArrayList<Publicity>();// 幼儿小班投票list
		List<Publicity> xxdnjPublicitys = new ArrayList<Publicity>();// 小学低年级投票list
		List<Publicity> xxznjPublicitys = new ArrayList<Publicity>();// 小学中年级投票list
		List<Publicity> xxgnjPublicitys = new ArrayList<Publicity>();// 小学高年级投票list

		int jzPublicitysNum = 0;
		int yedbPublicitysNum = 0;
		int yexbPublicitysNum = 0;
		int xxdnjPublicitysNum = 0;
		int xxznjPublicitysNum = 0;
		int xxgnjPublicitysNum = 0;

		for (Publicity publicity : publicitys) {
			if (publicity.getAgegroup().equals("0")) {// 家长学生
				if (jzPublicitys.size() <= 150) {
					jzPublicitys.add(publicity);
				}
			}

			if (publicity.getAgegroup().equals("7")) {// 幼儿大班
				if (yedbPublicitys.size() <= 150) {
					yedbPublicitys.add(publicity);
				}
			}

			if (publicity.getAgegroup().equals("8")) {// 幼儿小班
				if (yexbPublicitys.size() <= 150) {
					yexbPublicitys.add(publicity);
				}
			}

			if (publicity.getAgegroup().equals("9")) {// 小学低年级
				if (xxdnjPublicitys.size() <= 150) {
					xxdnjPublicitys.add(publicity);
				}
			}

			if (publicity.getAgegroup().equals("10")) {// 小学中年级
				if (xxznjPublicitys.size() <= 150) {
					xxznjPublicitys.add(publicity);
				}
			}

			if (publicity.getAgegroup().equals("11")) {// 小学高年级
				if (xxgnjPublicitys.size() <= 150) {
					xxgnjPublicitys.add(publicity);
				}
			}

		}

		// 计算6个分类的推荐人数
		for (Publicity publicity : jzPublicitys) {
			jzPublicitysNum += Integer.valueOf(publicity.getNumberofvote());

		}
		for (Publicity publicity : yedbPublicitys) {
			yedbPublicitysNum += Integer.valueOf(publicity.getNumberofvote());
		}
		for (Publicity publicity : yexbPublicitys) {
			yexbPublicitysNum += Integer.valueOf(publicity.getNumberofvote());
		}
		for (Publicity publicity : xxdnjPublicitys) {
			xxdnjPublicitysNum += Integer.valueOf(publicity.getNumberofvote());
		}
		for (Publicity publicity : xxznjPublicitys) {
			xxznjPublicitysNum += Integer.valueOf(publicity.getNumberofvote());
		}
		for (Publicity publicity : xxgnjPublicitys) {
			xxgnjPublicitysNum += Integer.valueOf(publicity.getNumberofvote());
		}

		return Msg.success().add("totle", totle).add("jzPublicitys", jzPublicitys).add("yedbPublicitys", yedbPublicitys).add("yexbPublicitys", yexbPublicitys).add("xxdnjPublicitys", xxdnjPublicitys).add("xxznjPublicitys", xxznjPublicitys).add("xxgnjPublicitys", xxgnjPublicitys).add("jzPublicitysNum", jzPublicitysNum).add("yedbPublicitysNum", yedbPublicitysNum).add("yexbPublicitysNum", yexbPublicitysNum).add("xxdnjPublicitysNum", xxdnjPublicitysNum).add("xxznjPublicitysNum", xxznjPublicitysNum).add("xxgnjPublicitysNum", xxgnjPublicitysNum);

	}

	// 修改榜单信息(修改书名和作者)
	@RequestMapping("/updPublicity")
	public Msg updPublicityContent(Publicity publicity) {
		if (publicity.getId() == 0) {
			return Msg.fail("参数错误");
		}
		boolean updresult = voteService.updPublicityContent(publicity);

		return Msg.judge(updresult);
	}

	// 获取学校列表
	@RequestMapping("/getSchoolList")
	public Msg getSchoolList() {
		// 获取所有用户
		List<User> users = voteService.getAllUser();
		List<String> schools = new ArrayList<String>();
		for (User user : users) {
			schools.add(user.getSchool());
		}

		// 去重
		schools = schools.stream().distinct().collect(Collectors.toList());

		return Msg.success().add("schools", schools);
	}

	// 获取城市列表
	@RequestMapping("/getCityList")
	public Msg getCityList() {
		// 获取所有用户
		List<User> users = voteService.getAllUser();
		List<String> citys = new ArrayList<String>();
		for (User user : users) {
			citys.add(user.getVoteaddress());
		}

		// 去重
		citys = citys.stream().distinct().collect(Collectors.toList());

		return Msg.success().add("citys", citys);
	}

	// 获取投过票的绘本列表
	@RequestMapping("/getPicbookList")
	public Msg getPicbookList() {
		// 获取所有用户
		List<Publicity> publicitys = voteService.getAllPublicity();
		List<String> picbooks = new ArrayList<String>();
		for (Publicity publicity : publicitys) {
			picbooks.add(publicity.getPicname());
		}

		// 去重
		picbooks = picbooks.stream().distinct().collect(Collectors.toList());

		return Msg.success().add("picbooks", picbooks);
	}

	// 对比方法
	@RequestMapping("/contrastRecord")
	public Msg contrastRecord(ContrastRecord contrastRecord) {// 对比
		// 判断对比什么
		if (contrastRecord.getPicname() == null || contrastRecord.getPicname().equals("")) {
			return Msg.fail("请输入对比的绘本");
		}

//		查询city1的投票数
		Integer count1;
		Integer count2;
		if (contrastRecord.getCity1().equals("") && contrastRecord.getCity2().equals("")) {// 如果城市1 2为空，则对比学校
			count1 = voteService.getSchoolCount(contrastRecord.getSchool1());
			count2 = voteService.getSchoolCount(contrastRecord.getSchool2());
		} else {// 对比城市
			count1 = voteService.getCityCount(contrastRecord.getCity1());
			count2 = voteService.getCityCount(contrastRecord.getCity2());
		}
		// 插如对比记录
		contrastRecord.setCount1(count1);
		contrastRecord.setCount2(count2);
		voteService.addContrastRecord(contrastRecord);

		// 返回对比结果
		return Msg.success().add("count1", count1).add("count2", count2);
	}

	// 查询历史对比列表
	@RequestMapping("/getCrList")
	public Msg getContrastRecordList() {
		List<ContrastRecord> contrastRecords = voteService.getContrastRecordList();

		return Msg.success().add("contrastRecords", contrastRecords);
	}

	// 通过历史对比列表id查询详情
	@RequestMapping("/getCrById")
	public Msg getContrastRecordById(String crid) {
		ContrastRecord contrastRecord = voteService.getContrastRecordById(crid);
		if (contrastRecord == null) {
			return Msg.fail();
		}
		return Msg.success().add("contrastRecord", contrastRecord);
	}
}
